package com.sdy.dcsb.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.sdy.common.model.Response;
import com.sdy.dcsb.biz.model.*;
import com.sdy.dcsb.biz.model.EsbSystemService;
import com.sdy.dcsb.biz.service.*;
import com.sdy.mvc.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;
import static org.springframework.util.StringUtils.isEmpty;

/**
 * <p>
 * 标准服务控制表 前端控制器
 * </p>
 *
 * @author fb
 * @since 2019-09-29
 */
@Slf4j
@Controller
@RequestMapping("/EsbSystemService")
@Api(tags = "服务的消费者使用次数控制相关接口")
public class EsbSystemServiceController extends BaseController {
    @Autowired
    private EsbSystemServiceService esbSystemServiceService;
    @Autowired
    private EsbServiceConsumerService esbServiceConsumerService;
    @Autowired
    private EsbConsumerSystemIpService esbConsumerSystemIpService;
    @Autowired
    private EsbConsumerSystemService esbConsumerSystemService;
    @Autowired
    private UserOperationLogService userOperationLogService;

    /**
     * 查询服务消费者信息
     * @param serviceid ,当前服务id
     * @param current ,当前页
     * @param size ,每页数量
     * @return
     */
    @GetMapping("/select")
    @ResponseBody
    @ApiOperation("查询服务消费者信息")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "serviceid", value = "当前服务id"),
            @ApiImplicitParam(dataType = "Integer", name = "current", value = "当前页"),
            @ApiImplicitParam(dataType = "Integer", name = "size", value = "每页数量"),
    })
    public Response select(Integer serviceid, Integer current, Integer size) {
        if(isEmpty(serviceid)) {
            return Response.error("请求的serviceid不能为空");
        }
        JSONObject object = new JSONObject();
        if(isEmpty(current)) {
            current = 1;
        }
        if(isEmpty(size)) {
            size = 10;
        }
        object.put("size",size);
        object.put("current",current);
        object.put("searchCount",true);
        Integer total = 0;
        Integer page = 0;
        List<EsbSystemServiceJoint> resultCount = esbSystemServiceService.findServiceConsumerCount(serviceid);
        total = resultCount.size();
        if(total%size==0){
            page = total/size;
        }else {
            page = total/size+1;
        }
        List<EsbSystemServiceJoint> result = esbSystemServiceService.findServiceConsumer(serviceid, current, size);
        object.put("records",result);
        object.put("total",total);
        object.put("pages",page);
        return Response.success(object);
    }

    /**
     * 删除当前服务下消费者
     * @param id ,当前流水id,EsbSystemService的id
     * @return
     */
    @GetMapping("/delete")
    @ResponseBody
    @ApiOperation("删除当前服务下的消费者")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "当前流水id,EsbSystemService的id"),
    })
    public Response delete(HttpServletRequest request, Integer id) {
        if(!isEmpty(id)) {
            EsbSystemService result = esbSystemServiceService.getById(id);
            String servCode = result.getServcode();
            Integer systemId = result.getSystemId();
            userOperationLogService.savaUserLog(request, "删除服务的消费者控制信息：" + servCode);
            if(esbSystemServiceService.removeById(id)) {
                QueryWrapper<EsbConsumerSystemIp> wrapper = new QueryWrapper<>();
                wrapper.eq("systemid",systemId);
                List<EsbConsumerSystemIp> ipIdResult = esbConsumerSystemIpService.list(wrapper);
                for(int i=0; i<ipIdResult.size(); i++) {
                    QueryWrapper<EsbServiceConsumer> esbServiceConsumerWrapper = new QueryWrapper<>();
                    esbServiceConsumerWrapper.eq("servcode", servCode);
                    esbServiceConsumerWrapper.eq("ipid", ipIdResult.get(i).getId());
                    userOperationLogService.savaUserLog(request, "删除服务的消费者ip权限信息：" + servCode +
                            " , " + ipIdResult.get(i).getId());
                    esbServiceConsumerService.remove(esbServiceConsumerWrapper);
                }
                return Response.success("删除消费者成功");
            }else {
                return Response.error("删除消费者失败！");
            }
        }else {
            return Response.error("请求id不能为空");
        }
    }

    /**
     * 查询当前服务下的一条消费者控制信息
     * @param id ,当前流水id,EsbSystemService的id
     * @return
     */
    @GetMapping("/selectOne")
    @ResponseBody
    @ApiOperation("查询当前服务下的一条消费者控制信息")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "当前流水id,EsbSystemService的id"),
    })
    public Response selectOne(Integer id) {
        if(!isEmpty(id)) {
            QueryWrapper<EsbSystemService> esbSystemServiceWrapper = new QueryWrapper<>();
            esbSystemServiceWrapper.eq("id",id);
            List<EsbSystemService> result = esbSystemServiceService.list(esbSystemServiceWrapper);
            Integer systemId = result.get(0).getSystemId();
            String systemName = esbConsumerSystemService.getById(systemId).getSystemName();
            JSONObject object = new JSONObject();
            object.put("id",result.get(0).getId());
            object.put("serviceid",result.get(0).getServiceid());
            object.put("servcode",result.get(0).getServcode());
            object.put("systemName",systemName);
            object.put("maxclient",result.get(0).getMaxclient());
            object.put("unit1",result.get(0).getUnit1());
            object.put("reqFrequency",result.get(0).getReqFrequency());
            return Response.success(object);
        }else {
            return Response.error("请求id不能为空");
        }
    }

    /**
     * 修改当前服务下消费者控制信息
     * @param id ,当前流水id,EsbSystemService的id
     * @param maxclient ,最大连接数
     * @param reqFrequency ,单位时间内请求数
     * @return
     */
    @GetMapping("/update")
    @ResponseBody
    @ApiOperation("修改当前服务下消费者控制信息")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "当前流水id,EsbSystemService的id"),
            @ApiImplicitParam(dataType = "Integer", name = "maxclient", value = "最大连接数"),
            @ApiImplicitParam(dataType = "String", name = "reqFrequency", value = "单位时间内请求数"),
    })
    public Response update(HttpServletRequest request, Integer id, Integer maxclient, String reqFrequency) {
        if(isEmpty(id)) {
            return Response.error("请求id不能为空");
        }
        if(!isEmpty(maxclient) || isEmpty(reqFrequency)) {
            try {
                reqFrequency = URLDecoder.decode(reqFrequency,"utf-8");
            }catch(IOException e) {

            }
            EsbSystemService esbSystemService = new EsbSystemService();
            esbSystemService.setMaxclient(maxclient);
            esbSystemService.setReqFrequency(reqFrequency);
            userOperationLogService.savaUserLog(request, "修改服务的消费者控制信息：" +
                    esbSystemServiceService.getById(id).getServcode());
            return Response.success(esbSystemServiceService.update(esbSystemService, new UpdateWrapper<EsbSystemService>().eq("id", id)));
        }else {
            return Response.error("修改参数不能为空");
        }
    }

    /**
     * 新增服务的消费者信息
     * @param serviceid ,当前服务id
     * @param servcode ,当前服务编码
     * @param systemId ,添加的消费者系统id
     * @return
     */
    @GetMapping("/insert")
    @ResponseBody
    @ApiOperation("新增服务的消费者信息")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "serviceid", value = "当前服务id"),
            @ApiImplicitParam(dataType = "String", name = "servcode", value = "当前服务编码"),
            @ApiImplicitParam(dataType = "Integer", name = "systemId", value = "添加的消费者系统id"),
    })
    public Response insert(HttpServletRequest request, Integer serviceid, String servcode, Integer[] systemId) {
        if(isEmpty(serviceid)) {
            return Response.error("服务id不能为空");
        }
        if(isEmpty(servcode)) {
            return Response.error("服务编码不能为空!");
        }

        try {
            servcode = URLDecoder.decode(servcode,"utf-8");
        }catch(IOException e) {

        }

        for(int j =0; j<systemId.length; j++ ) {

            QueryWrapper<EsbSystemService> esbSystemServiceWrapper = new QueryWrapper<>();
            esbSystemServiceWrapper.eq("serviceid",serviceid);
            esbSystemServiceWrapper.eq("system_id",systemId[j]);
            List<EsbSystemService> esbSystemServiceWrapperResult = esbSystemServiceService.list(esbSystemServiceWrapper);
            if(esbSystemServiceWrapperResult.size() != 0 ){
                return Response.error("新增失败，当前服务已添加过此消费者！(消费者系统id为："+ systemId[j] +")请重新选择");
            }

            EsbSystemService esbSystemService = new EsbSystemService();
            esbSystemService.setServiceid(serviceid);
            esbSystemService.setServcode(servcode);
            esbSystemService.setSystemId(systemId[j]);
            esbSystemService.setMaxclient(20);
            esbSystemService.setUnit1("86400");
            esbSystemService.setReqFrequency("2000");
            userOperationLogService.savaUserLog(request, "新增服务的消费者控制信息：" + servcode);
            if(esbSystemServiceService.save(esbSystemService)) {
                QueryWrapper<EsbConsumerSystemIp> wrapper = new QueryWrapper<>();
                wrapper.eq("systemid",systemId[j]);
                List<EsbConsumerSystemIp> result = esbConsumerSystemIpService.list(wrapper);
                for(int i=0; i<result.size(); i++) {
                    Integer ipid = result.get(i).getId();
                    EsbServiceConsumer esbServiceConsumer = new EsbServiceConsumer();
                    esbServiceConsumer.setServcode(servcode);
                    esbServiceConsumer.setIpid(ipid);
                    esbServiceConsumer.setStatus("0");
                    esbServiceConsumer.setCreateTime(new Date());
                    esbServiceConsumer.setUpdateTime(new Date());
                    userOperationLogService.savaUserLog(request, "新增服务的消费者ip权限信息："
                            + servcode + " , " + ipid);
                    if(!esbServiceConsumerService.save(esbServiceConsumer)) {
                        return Response.error("ip新增失败！");
                    }
                }
            }else {
                return Response.error("服务消费者系统新增失败！");
            }
        }
        return Response.success("服务新增消费者成功！");
    }

}
